package com.zensun.common.core.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zensun.common.core.page.PageDataInfo;
import com.zensun.common.core.page.PageDomain;
import com.zensun.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;

/**
 * web层通用数据处理
 *
 * @author gmk
 */
@Slf4j
public class BaseController {

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = new PageDomain();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (ObjectUtil.isNull(pageNum) || ObjectUtil.isNull(pageSize)) {
            pageNum = 1;
            pageSize = 10;
        }
        String orderBy = pageDomain.getOrderBy();
        if (StrUtil.isNotBlank(orderBy)) {
            PageHelper.startPage(pageNum, pageSize, orderBy);
        } else {
            PageHelper.startPage(pageNum, pageSize);
        }

    }

    /**
     * 响应请求分页数据
     *
     * @param list
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected PageDataInfo getPageDataTable(List<?> list) {
        PageInfo pageInfo = new PageInfo(list);
        PageDataInfo pageData = new PageDataInfo();
        pageData.setList(list);
        pageData.setPageNum(pageInfo.getPageNum());
        pageData.setPageSize(pageInfo.getPageSize());
        pageData.setPages(pageInfo.getPages());
        pageData.setSize(pageInfo.getSize());
        pageData.setTotal(pageInfo.getTotal());
        return pageData;
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StrUtil.format("redirect:{}", url);
    }
}
